package com.daxia.ogmall.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.daxia.ogmall.dto.GPSAddressDTO;
import com.daxia.ogmall.model.City;
import com.daxia.ogmall.util.MyWebUtils;

@Controller
@RequestMapping(value = "util", produces="text/html;charset=UTF-8")
public class UtilController extends BaseController {
	private static Logger logger = Logger.getLogger(UtilController.class);
	
	@ResponseBody
	@RequestMapping("getCity")
	public String getCity(HttpServletRequest request) throws Exception {
		City city = getCurrentCity();
		if (city == null) {
		    GPSAddressDTO dto = locationService.getGPSAddressByIP(request.getRemoteHost());
		    if (dto != null && dto.getCity() != null) {
		    	city = dto.getCity();
		    } else {
		    	city = locationService.getDefaultAddress().getCity();
		    }
		}
		String ret = null;
		if (city != null) {
			MyWebUtils.getCurrentRequest().getSession().setAttribute("currentCity", city);
			ret = city.getName();
		} else {
			ret = "东莞市";
		}
		logger.error("util/getCity, ip: " + request.getRemoteHost() + ", result: " + ret);
		return ret;
	}

	private City getCurrentCity() {
		return (City) MyWebUtils.getCurrentRequest().getSession().getAttribute("currentCity");
	}
}	